<template>
	<div class="contain">
		<div class="hd mt10">
			<img src="../../assets/yygh.png" alt="">
		</div>
		<search-bar></search-bar>
		<div class="content">
			<position>
				<router-link to="/yygh">预约挂号</router-link>
				&gt;
				<span class="last">支付</span>
			</position>
			<steps :step="2"></steps>
      <free :freeDialog="freeDialog" :nextUrl="nextUrl" :type="type"></free>
			<div class="border_content bg-white">

				<div class="price">
					<span>挂号费：</span>
					<span>{{dep.charge}}</span>
					<span>元</span>
				</div>
				<div class="border"></div>

				<div class="pay_left_time" v-if="outTime && !showSVG">
					<span class="error">您的订单已经失效！请重新预约</span>
				</div>
				<div class="pay_left_time" v-if="!outTime && !showSVG">
					<span>支付剩余时间</span>
					<span> {{m}}:{{s}}</span>
					<span>，超时自动失效</span>
				</div>

				<div v-if="!showSVG">
					<div class="pay_type_title">
						<p>请选择支付方式</p>
					</div>
					<div class="pay_type">
						<div class="zhifubao">
							<el-radio v-model="radio" label="02"> <img src="../../assets/支付宝.png" alt=""></el-radio>&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
							<span>推荐支付宝账户使用</span>
						</div>
						<div class="wechat">
							<el-radio v-model="radio" label="03"> <img src="../../assets/微信支付.png" alt=""> </el-radio>
							&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
							<span>微信快捷支付</span>
						</div>
					</div>
					<div class="border"></div>
					<div class="button" v-if="outTime">
						<router-link to="/yygh">返回</router-link>
					</div>
					<div class="button" v-else>
						<a href="javascript:;" class="common-main-button" @click="submitPay">下一步</a>

					</div>
				</div>
				<div v-else class="hd" style="width:512px;margin:40px auto;">
					<div class="qrcode-wrapper" v-if="this.radio === '02'">
						<div v-html="qrcodeSrc" class="qrcode alipay"></div>
					</div>

					<div class="qrcode-wrapper wxpay" v-if="this.radio === '03'">
						<div v-html="qrcodeSrc" class="qrcode wxpay"></div>
					</div>

					<div class="qrcode-text ">二维码有效时间
						<span class="t1">{{qrcodeSeconds}}</span> 秒</p>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import QRCode from 'qr-image'
import { leftTime } from '../../common/js/util'
import Steps from '../../components/Steps'
import SearchBar from '../../components/SearchBar'
import position from '../../components/Position'
import free from '../../components/free.vue'
import { commonAjax, ORG_ID, PLATFORM_PREFIX, SUBMIT_SOURCE} from '../../api/api'
export default {
	data() {
		return {
			m: 0,
			s: 0,
			outTime: false,
			dep: JSON.parse(localStorage.dep),
			order: JSON.parse(localStorage.order),
			time: JSON.parse(localStorage.time),
			list: {},
			radio: '02',
			qrcodeSrc: '',
			showSVG: false,
			timer: null,
			qrcodeSeconds: 60,
			payTypeName: '支付宝',
      freeDialog: false,
      nextUrl: '/yygh/PayResult',
      type: 'appoint'
		}
	},
	mounted() {
		this.resetVars()
		this.preBudget()
		const ORDER_OUT_DATE_TIME = 0
		let _this = this
		this.$store.commit('UPDATE_LOADING')
		commonAjax([], `${PLATFORM_PREFIX}.appService`, 'getServerTime').then(res => {
			this.$store.commit('UPDATE_LOADING')
    	if (res.data.code === 200) {
				console.log(`get server time: ${res.data.body.serverTime}`)
				let orderCreateTime = new Date(this.order.regCloseTimeDisplay.replace(/-/g, '/'))
				let dist = new Date(res.data.body.serverTime.replace(/-/g, '/')) - new Date()
				let timer = setInterval(() => {
					var left = leftTime(ORDER_OUT_DATE_TIME, (dist + (new Date() - orderCreateTime)))
					if (left.m <= 0 && left.s <= 0) {
						clearInterval(timer)
						_this.outTime = true
					} else {
						_this.m = left.m
						_this.s = left.s
					}
				}, 1000)
			}
		})
	},
	beforeDestroy() {
		// important
		clearInterval(this.timer)
	},
	methods: {
		resetVars() {
			if (this.$route.query.from === 'myappoint') {
				this.list = JSON.parse(localStorage.list)
				this.dep.charge = this.list.charge
				this.order.regRecordId = this.list.regRecordId
				this.order.regCloseTimeDisplay = this.list.regCloseTimeDisplay
			}
		},
		preBudget () {
			// 预结算费用
			commonAjax([this.order.regRecordId, ORG_ID, localStorage.appointType || 1], `${PLATFORM_PREFIX}.registrationService`, 'preBudget').then(res => {
				if (res.data.code === 200) {
					this.dep.charge = res.data.body.selfAmount
          if (parseFloat(this.dep.charge === 0)) {
					  this.freeDialog = true
          }
				} else {
          this.$message({
            message: res.data.code,
            type: 'error'
          })
        }
			})
		},
		submitPay() {
			let config = {
				orgId: ORG_ID,
				totalAmount: this.dep.charge,
				accountType: this.radio,
				body: JSON.stringify({ bustype: '11', id: this.order.regRecordId, source: SUBMIT_SOURCE}),
				outTradeNo: this.order.regSourceId,
				closePayTime: this.order.regClosePayTime,
				payModel: '2'
			}
			this.$store.commit('UPDATE_LOADING')
			if (this.$route.query.from === 'myappoint') {
				config = {
					orgId: ORG_ID,
					totalAmount: this.list.charge,
					accountType: this.radio,
					body: JSON.stringify({ bustype: '11', id: this.list.regRecordId, source: SUBMIT_SOURCE}),
					outTradeNo: this.list.regSourceId,
					closePayTime: this.list.regCloseTimeDisplay,
					payModel: '2'
				}
			}
			commonAjax(
				[config],
				`${PLATFORM_PREFIX}.payService`,
				'getOrderStr'
			).then(res => {
				this.$store.commit('UPDATE_LOADING')
				if (res.data.code === 200) {
					let _this = this
					this.qrcodeSrc = QRCode.imageSync(res.data.body, { type: 'svg' })
					this.showSVG = true
					if (this.radio === '03') {
						this.payTypeName = '微信'
					}
					let qrtimer = setInterval(() => {
						if (_this.qrcodeSeconds <= 0) {
							clearInterval(qrtimer)
						} else {
							_this.qrcodeSeconds--
						}
					}, 1000)
					if (this.timer) {
						clearInterval(this.timer)
					}
					this.queryAliOrder()
				} else {
					this.$message({
						message: '请求服务端失败',
						type: 'error'
					})
				}
			}).catch(res => {
				this.$store.commit('UPDATE_LOADING')
				this.$message({
					message: '请求服务端失败',
					type: 'error'
				})
			})
		},
		queryAliOrder() {
			let i = 0
			const TIME_OUT = 60  // 支付二维码超时时间（秒）
			const PER_TIME = 3	// 轮询间隔（秒）
			let _this = this
			this.timer = setInterval(() => {
				i++
				commonAjax([{
					orgId: ORG_ID,
					outTradeNo: this.order.regSourceId,
					accountType: this.radio
				}], `${PLATFORM_PREFIX}.payService`, 'queryAliOrder').then(res => {
					if (res.data.body) {
						this.$router.push('/yygh/payresult?result=victory')
					} else if (i < (TIME_OUT / PER_TIME)) {
						console.log('checking order status...' + i)
					} else {
						clearInterval(_this.timer)
						this.$router.push('/yygh/payresult?result=defeat')
					}
				})
			}, PER_TIME * 1000)
		}
	},
	components: {Steps, position, SearchBar, free}
}
</script>

<style lang="less">
.contain {
	margin-bottom: 100px;
	.content {
		width: 1080px;
		margin: 0 auto;
		background-color: #ffffff;
		overflow: hidden;
	}
	.content .flow {
		margin-top: 20px;
	}
	.border_content .price {
		margin-left: 48px;
		margin-top: 50px;
	}
	.border_content .border {
		width: 1010px;
		margin: 0 auto;
		height: 1px;
		background-color: rgb(245, 230, 227);
		margin-top: 30px;
	}
	.border_content .price span:nth-of-type(1) {
		font-size: 18px;
		display: inline-block;
	}
	.border_content .price span:nth-of-type(2) {
		font-size: 18px;
		display: inline-block;
		color: #993333;
	}
	.border_content .price span:nth-of-type(3) {
		font-size: 18px;
	}
	.border_content .pay_left_time {
		margin-left: 48px;
		margin-top: 24px;
	}
	.border_content .pay_left_time span:nth-of-type(1) {
		font-size: 16px;
		color: #ff9900;
	}
	.border_content .pay_left_time span:nth-of-type(2) {
		font-size: 16px;
		color: #993333;
	}
	.border_content .pay_left_time span:nth-of-type(3) {
		font-size: 16px;
		color: #ff9900;
	}
	.border_content .pay_type_title {
		margin-top: 44px;
		margin-left: 48px;
		color: #666666;
		font-size: 14px;
	}
	.border_content .pay_type {
		width: 1016px;
		height: 156px;
		background-color: rgb(254, 251, 248);
		margin: 0 auto;
		overflow: hidden;
	}
	.border_content .pay_type img {
		vertical-align: middle;
	}
	.border_content .pay_type .zhifubao {
		margin-top: 30px;
		margin-left: 20px;
	}
	.border_content .pay_type .wechat {
		margin-top: 30px;
		margin-left: 20px;
	}
	.border_content .button {
		margin-left: 58px;
		margin-top: 30px;
		padding-bottom: 60px;
	}
	.border_content .button a:nth-of-type(1) {
		display: inline-block;
		width: 128px;
		height: 40px;
		background: url(../../assets/前往付费.png) 0 0 no-repeat;
		background-size: 100% 100%;
		text-align: center;
		line-height: 40px;
		color: #ffcc99;
	}
	.border_content .button a:nth-of-type(2) {
		display: inline-block;
		width: 128px;
		height: 40px;
		background: url(../../assets/返回.png) 0 0 no-repeat;
		background-size: 100% 100%;
		text-align: center;
		line-height: 40px;
		color: #663300;
		margin-left: 10px;
	}
	.qrcode-wrapper {
		width: 512px;
		height: 678px;
		background: url(../../assets/payType.jpg) no-repeat;
		position: relative;
		&.wxpay {
			background-position: -512px 0;
		}
	}
	.qrcode {
		width: 170px;
		height: 170px;
		border-radius: 10px;
		position: absolute;
		top: 250px;
		left: 170px;
	}
	.qrcode-text {
		margin: 20px;
		text-align: center;
	}
}
</style>
